package com.zw.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zw.common.constant.WareConstant;
import com.zw.common.utils.BeanUtils;
import com.zw.gulimall.ware.entity.PurchaseDetailEntity;
import com.zw.gulimall.ware.service.PurchaseDetailService;
import com.zw.gulimall.ware.service.WareSkuService;
import com.zw.gulimall.ware.vo.PurchaseDoneVo;
import com.zw.gulimall.ware.vo.PurchaseItemDoneVo;
import com.zw.gulimall.ware.vo.PurchaseMergeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.common.utils.PageUtils;
import com.zw.common.utils.Query;

import com.zw.gulimall.ware.dao.PurchaseDao;
import com.zw.gulimall.ware.entity.PurchaseEntity;
import com.zw.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;



@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPagePurchaseUnReceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>()
                        .eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        .or()
                        .eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public Boolean merge(PurchaseMergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if (Objects.isNull(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = vo.getItems().stream().map(x -> {
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            detail.setPurchaseId(finalPurchaseId);
            detail.setId(x);
            detail.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
            return detail;
        }).collect(Collectors.toList());

        if(purchaseDetailService.checkPurchaseStatus(list)){
            purchaseDetailService.updateBatchById(list);

//        维护purchase表
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(finalPurchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.saveOrUpdate(purchaseEntity);
            return true;
        };
        return false;
    }

    @Override
    public void received(List<Long> list) {
//        确认当前采购单的状态(新建或者已分配)
        List<PurchaseEntity> entityList = baseMapper.selectList(new LambdaQueryWrapper<PurchaseEntity>()
                .in(PurchaseEntity::getId, list));
        List<PurchaseEntity> collect = entityList.stream()
                .filter(x -> Objects.equals(x.getStatus(), WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        || Objects.equals(x.getStatus(), WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                }).collect(Collectors.toList());
//        改变采购单的状态
        this.updateBatchById(collect);
//        改变采购项的状态
        List<Long> ids = collect.stream().map(item -> item.getId()).collect(Collectors.toList());
        detailService.updatePurchaseDetailStatusByPurchaseIds(ids);
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo vo) {
//        更改采购需求的状态
        List<PurchaseItemDoneVo> items = vo.getItems();
        AtomicBoolean flag = new AtomicBoolean(true);
        List<PurchaseDetailEntity> collect = items.stream().map(purchaseItemDoneVo -> {
            PurchaseDetailEntity entity1 = purchaseDetailService.getById(purchaseItemDoneVo.getItemId());
            PurchaseDetailEntity entity = BeanUtils.copyProperties(entity1, PurchaseDetailEntity::new);
//            entity.setId(purchaseItemDoneVo.getItemId());
            if (entity.getStatus() != WareConstant.PurchaseStatusEnum.FINISH.getCode()) {
                flag.set(false);
            }
            entity.setStatus(purchaseItemDoneVo.getStatus());
//            entity.setPurchaseId(vo.getId());
            return entity;
        }).collect(Collectors.toList());
        purchaseDetailService.saveOrUpdateBatch(collect);
//        更改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(vo.getId());
        purchaseEntity.setUpdateTime(new Date());

        if(flag.get()){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }

        this.updateById(purchaseEntity);
//        入库
        wareSkuService.saveOrUpdateBatchWareSku(collect);
    }
}
